package com.mediacloud.app.newsmodule.fragment.ws

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.newsmodule.utils.NewsListDataInvoker
import com.mediacloud.app.newsmodule.utils.VideoAddressGet
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.tencent.mmkv.MMKV
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_ws24_filter.*
import org.json.JSONObject

class WS24FilterActivity : BaseBackActivity(),
    OnRefreshLoadMoreListener {
    override fun showTitleBar() = false
    var adapter: BaseQuickAdapter<TimeLineItem, BaseViewHolder>? = null
    protected var pageNum = 1
    protected var pageSize = 200
    var publish_date_start: String? = null
    var publish_date_end: String? = null
    var catalogID: String? = ""
    var catalog: CatalogItem? = null
    var hasMore = false
    override fun getLayoutResID(): Int {
        return R.layout.activity_ws24_filter
    }

    override fun onDestroy() {
        super.onDestroy()
        mDisposable?.dispose()
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.publish_date_start = intent?.getStringExtra("DATE")
        titleTv.text = this.publish_date_start
        this.publish_date_end = this.publish_date_start
        catalogID = intent?.getStringExtra("NAV_ID")
        catalog = intent?.getParcelableExtra("CATALOG")
        initStateView()
        loadingView = findViewById(R.id.mLoadingView)
        retryTips?.setOnClickListener {
            pageNum = 1
            getNewsListData()
        }

        initStateView()
        showStateView(TYPE_LOADING, false)

        refreshLayout.setOnRefreshLoadMoreListener(this)

        recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = WS24ListAdapter()
        recyclerView.adapter = adapter
        adapter?.bindToRecyclerView(recyclerView)
        backIco.setOnClickListener {
            finish()
        }
//        adapter?.setEmptyView(R.layout.empty_ws24, recyclerView)
        adapter?.setOnItemClickListener { adapter, view, position ->
            val _item = adapter.getItem(position)
            if (_item is TimeLineItem) {
                val item = ArticleItem()
                item.id = _item.id
                item.title = _item.title
                item.type =_item.type
                item.logo =_item.logo
                item.positionInList = position
                item.parentId = catalogID
                item.url = _item.url
                MMKV.defaultMMKV().putBoolean(item.getId().toString() + "", true)
                adapter?.notifyItemChanged(position)
                NewsItemClickUtils.OpenItemNewsHandle(
                    this,
                    item.getType(),
                    item,
                    catalog ?: CatalogItem()
                )
            }
        }

        getNewsListData()
    }


    var mDisposable: Disposable? = null
    override fun getStatusBarColor() = Color.WHITE


    fun getNewsListData() {

        val map: MutableMap<String, String> = java.util.HashMap()
        if (!TextUtils.isEmpty(publish_date_start)) {
            map["publish_date_start"] = "$publish_date_start"
        }
        if (!TextUtils.isEmpty(publish_date_end)) {
            map["publish_date_end"] = "$publish_date_end"
        }
        map["no_content"] = "1"
        map["client"] = DataInvokeUtil.ClientFlag
        map["page"] = "" + pageNum
        map["perPage"] = "" + pageSize
        map["navigate_id"] = "$catalogID"

        val d = DataInvokeUtil.ziMeiTiApi
            .getTimeLine( map)
            .subscribeOn(Schedulers.io())
            .map {
                hasMore = false
                val state = it.body()?.optBoolean("state") ?: false
                val dataList: MutableList<TimeLineItem> = java.util.ArrayList()
                if (state) {
                    it.body()?.optJSONObject("data")?.let {
                        val paging = it.optJSONObject("paging")
                        paging?.let {
                            hasMore = it.optInt("currentPage") < it.optInt("lastPage")
                        }
                        it.optJSONArray("meta")?.let {
                            val size = it.length()
                            for (i in 0 until size) {
                                val obj = it.optJSONObject(i)
                                val type = obj.optInt("type")
                                if (type == TypeX.NEWS.VIDEO || type == TypeX.NEWS.MICRO_LIVE||type == TypeX.NEWS.LITE_AV){
                                    var video: JSONObject
                                    try {
                                        video = obj.optJSONObject("video")
                                    }catch (e:Exception){
                                        video = JSONObject("")
                                    }
                                    val videoItem = TimeLineItem(
                                        obj.optLong("id"),
                                        obj.optString("title"),
                                        obj.optString("publishdate"),
                                        obj.optString("publishdate_format"),
                                        type,
                                        obj.optString("logo"),
                                        obj.optString("prop4"),
                                        video.toString()
                                    )
                                    videoItem.author = obj.optString("Author")
                                    videoItem.referName = obj.optString("ReferName")
                                    videoItem.url = obj.optString("url")
                                    dataList.add(
                                        videoItem
                                    )
                                }else{
                                    val item = TimeLineItem(
                                        obj.optLong("id"),
                                        obj.optString("title"),
                                        obj.optString("publishdate"),
                                        obj.optString("publishdate_format"),
                                        type,
                                        obj.optString("logo"),
                                        obj.optString("prop4"),
                                        ""
                                    )
                                    item.author = obj.optString("Author")
                                    item.referName = obj.optString("ReferName")
                                    item.url = obj.optString("url")
                                    dataList.add(item)
                                }
                            }
                        }
                    }
                }
                dataList
            }.subscribeOn(Schedulers.io())
            .onErrorReturn { null }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<MutableList<TimeLineItem>> {
                override fun onSubscribe(d: Disposable) {
                    mDisposable = d
                }

                override fun onNext(t: MutableList<TimeLineItem>) {
                    if (isFinishing || isDestroyed) {
                        return
                    }
                    refreshLayout?.finishLoadMore()
                    refreshLayout?.finishRefresh()

                    if (pageNum == 1) {
                        adapter?.setNewData(t)
                        if (pageNum == 1 && t.size > 0) {
                            recyclerView.scrollToPosition(0)
                        }
                    } else {
                        adapter?.addData(t)
                    }
                    refreshLayout?.setNoMoreData(!hasMore)

                    if (adapter!!.data.size == 0) {
                        showStateView(TYPE_NO_CONTENT, false)
                    } else {
                        closeStateView()
                    }
                }

                override fun onError(e: Throwable) {
                    if (isFinishing || isDestroyed) {
                        return
                    }
                    refreshLayout?.finishLoadMore()
                    refreshLayout?.finishRefresh()

                    if (adapter?.data?.size!! > 0) {
                        if (pageNum == 1) {
                            adapter?.setNewData(ArrayList())
                        }
                    } else {
                        showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                    }
                    adapter?.notifyDataSetChanged()
                }

                override fun onComplete() {
                }
            })
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        pageNum = 1
        getNewsListData()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        pageNum++
        getNewsListData()
    }
}